"use client";
import React, { useEffect, useState } from "react";
import useSWR from "swr";
import { fetcher } from "@/app/libs/index";
import PostRegion from "@/app/components/region/Post";
import { PostModel, Region } from "@/app/types/region";
import Link from "next/link";

export default function Posts() {
    const [posts, setPosts] = useState<PostModel[]>([]);
    const [regions, setRegions] = useState<Region[]>([]);
    const { data, error, isLoading } = useSWR<any>(`/region/1`, fetcher);

    useEffect(() => {
        if (data && data.result.data) {
            console.log(data.result.data);
            setPosts(data.result.data);
        }
    }, [data, isLoading]);

    useEffect(() => {
        fetchRegions().then((newRegions) => setRegions(newRegions));
    }, []);

    const fetchRegions = async () => {
        const res = await fetch(`/region`);
        const data = await res.json();
        return data.result.data;
    };

    let delete_Post: PostModel['deletePost'] = async (id: number) => {
        const res = await fetch(`/region/${id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        const content = await res.json();
        if (content.success > 0) {
            setPosts(posts?.filter((post: PostModel) => post.id !== id));
        }
    };

    return (
        <div className="w-full max-w-7xl m-auto">
            <table className="w-full border-collapse border border-slate-400">
                <caption className="caption-top py-5 font-bold text-green-500 text-2xl">
                    List Posts - Counter :
                    <span className="text-red-500 font-bold">{posts?.length}</span>
                </caption>

                <thead>
                <tr className="text-center">
                    <th className="border border-slate-300">ID</th>
                    <th className="border border-slate-300">Title</th>
                    <th className="border border-slate-300">Region</th>
                    <th className="border border-slate-300">Created at</th>
                    <th className="border border-slate-300">Modify</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td colSpan={5}>
                        <Link href={`/post/create`} className="bg-green-500 p-2 inline-block text-white">
                            Create
                        </Link>
                    </td>
                </tr>
                {posts &&
                    posts.map((item: PostModel) => (
                        <PostRegion key={item.id} {...item} deletePost={delete_Post} regions={regions} />
                    ))}
                </tbody>
            </table>
        </div>
    );
}

// Update the PostRegion component to receive regions as a prop
interface PostProps extends PostModel {
    deletePost: (id: number) => void;
    regions: Region[];
}

const Post: React.FC<PostProps> = ({ id, title, regionId, createdAt, regions, deletePost }) => {
    const region = regions.find((region) => region.id === parseInt(regionId));
    const regionName = region ? region.name : "Unknown";

    return (
        <tr className="text-center">
            <td className="border border-slate-300">{id}</td>
            <td className="border border-slate-300">{title}</td>
            <td className="border border-slate-300">{regionName}</td>
            <td className="border border-slate-300">{createdAt}</td>
            <td className="border border-slate-300">
                <button onClick={() => deletePost(id)}>Delete</button>
            </td>
        </tr>
    );
};